package html;

import gui.ava.html.Html2Image;
import gui.ava.html.renderer.ImageRenderer;
import org.apache.commons.codec.binary.Base64;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.UUID;

public class Html2Img {

    /**
     * 使用Html2Image将html转图片
     */
    public static void main(String[] args) {
        String imageHtml = "<p><span style=\"font-size:30px\"><strong><span style=\"color:#c0392b\"><p>姓名：哈哈哈哈</p><p>地址：8888</p><p>公司：9999</p></span></strong></span></p>";

        // Html2Image html2Image = Html2Image.fromHtml(imageHtml);

        Html2Image html2Image = Html2Image.fromFile(new File("D:\\export_tmp\\ToHtmlWithImageEmbeded.html"));
        // HtmlIm
        // ageMap htmlImageMap = html2Image.getHtmlImageMap();
        ImageRenderer imageRenderer = html2Image.getImageRenderer();

        // 方式1：保存图片文件
        // Caused by: java.io.FileNotFoundException: D:\opt\b84a28f1-b372-4298-932b-a92ef39f5c64.png
        // opt目录不存在会报错
        String imageName = "D:\\export_tmp\\" + UUID.randomUUID().toString() + ".png";
        imageRenderer.saveImage(imageName);

        // 方式2：响应图片流
        BufferedImage bufferedImage = imageRenderer.getBufferedImage();

        // try (FileOutputStream out = new FileOutputStream(imageName);) {
        //     ImageIO.write(bufferedImage, "png", out);
        // } catch (Exception e) {
        //     e.printStackTrace();
        // }

        // 方式3：转base64
        try (ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream()) {
            ImageIO.write(bufferedImage, "png", byteOutputStream);
            String base64Img = Base64.encodeBase64String(byteOutputStream.toByteArray());
            String res = "data:image/jpg;base64," + base64Img.toString();
            System.out.println(res);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
